<template>
  <div class="read-more-line">
    <div class="u-wrap" :style="style">
      <div class="u-content" ref="contentRef">
        <span v-html="content"></span>
        <div
          class="u-more-wrap"
          v-show="isOverLimit && !showAll"
          @click="showAll = true"
        >
          <slot name="more">
            <span class="u-text">...更多</span>
          </slot>
        </div>
        <span
          class="u-less-wrap"
          v-show="isOverLimit && showAll"
          @click="showAll = false"
        >
          <slot name="less">
            <span class="u-text">收起</span>
          </slot>
        </span>
      </div>
    </div>
  </div>
</template>

<script setup name="ReadMoreLine">
import { computed, ref } from 'vue'
import { watch } from 'vue'

const props = defineProps({
  content: String,
  limit: {
    type: Number,
    default: 3,
  },
  lineHeight: {
    type: Number,
    default: 30,
  },
})

const contentRef = ref()
// 是否超高
const isOverLimit = ref(false)
// 是否处于展开状态
const showAll = ref(false)

const style = computed(() => {
  const obj = {}
  isOverLimit.value &&
    showAll.value === false &&
    (obj.height = `${props.limit * props.lineHeight}px`)
  obj.lineHeight = `${props.lineHeight}px`
  return obj
})

// 检查是否超高
function checkOverLimit() {
  if (contentRef.value) {
    isOverLimit.value =
      contentRef.value.offsetHeight > props.limit * props.lineHeight
  }
}

watch(
  [() => props.content, contentRef],
  () => {
    checkOverLimit()
  },
  { immediate: true }
)
</script>

<style lang="stylus" scoped>
.read-more-line
  position relative
  overflow hidden
  .u-more-wrap
    position absolute
    right 0
    bottom 0
    background #fff
    cursor pointer
    .u-text
      padding-left 4px
  .u-less-wrap
    float right
    cursor pointer
  .u-text
    color var(--el-color-primary)
    white-space nowrap
    &:hover
      color var(--el-color-primary-light-3)
</style>
